package com.tencent.sr.iris.activity.service.task.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.tencent.sr.iris.activity.common.constant.QuFaHttpConstant;
import com.tencent.sr.iris.activity.common.util.ScrmServerHttpUtil;
import com.tencent.sr.iris.activity.dependency.ActivityMessageDependency;
import com.tencent.sr.iris.activity.dependency.basic.BasicDependency;
import com.tencent.sr.iris.activity.dependency.qufa.GroupTaskDependency;
import com.tencent.sr.iris.activity.interfaces.request.task.*;
import com.tencent.sr.iris.activity.interfaces.request.task.scrm.MarketTaskScrmRequest;
import com.tencent.sr.iris.activity.interfaces.response.activity.MarketCalendarScrmResponse;
import com.tencent.sr.iris.activity.interfaces.response.group.task.*;
import com.tencent.sr.iris.activity.service.constant.MarketCalendarConstants;
import com.tencent.sr.iris.activity.service.task.GroupTaskService;
import com.tencent.sr.iris.basic.service.interfaces.dto.TCommonKvConfigDTO;
import com.tencent.sr.iris.basic.service.interfaces.request.ActivityQuerySubscribeRequest;
import com.tencent.sr.iris.basic.service.interfaces.request.TCommonKvConfigBatchQueryRequest;
import com.tencent.sr.iris.basic.service.interfaces.response.ActivityQuerySubscribeResponse;
import com.tencent.sr.rmall.common.request.PaginationRequest;
import com.tencent.sr.rmall.common.response.PaginationResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

@Slf4j
@Component
public class GroupTaskServiceImpl implements GroupTaskService {

    @Resource
    private GroupTaskDependency groupTaskDependency;
    @Resource
    private ActivityMessageDependency activityMessageDependency;

    @Resource
    private ScrmServerHttpUtil scrmServerHttpUtil;

    @Resource
    private BasicDependency basicDependency;

    @Override
    public GroupTaskRewardResponse taskReward(GroupTaskRewardRequest request) {
        return groupTaskDependency.getGroupTaskReward(request.getUnionId());
    }

    @Override
    public PaginationResponse<GroupTaskRewardDetailResponse> pageRewardList(
            PaginationRequest<GroupTaskRewardDetailRequest> request) {
        return groupTaskDependency.pageGroupTaskRewardList(request);
    }

    @Override
    public GroupTaskConfigResponse config() {
        return groupTaskDependency.config();
    }

    @Override
    public GroupTaskPopResponse pop(GroupTaskPopRequest request) {
        return groupTaskDependency.pop(request);
    }

    @Override
    public PaginationResponse<GroupTaskListResponse> listInProgress(
            PaginationRequest<GroupTaskListNewRequest> request) {

        Integer pageNum = request.getPageNum();
        Integer pageSize = request.getPageSize();
        PaginationResponse<GroupTaskListResponse> page = new PaginationResponse<>();
        page.setPageNum(pageNum);
        page.setPageSize(pageSize);
        page.setDataList(Lists.newArrayList());
        page.setTotalCount(0);

        List<GroupTaskListResponse> groupTaskListResponses = groupTaskDependency.listInProgress(
                request.getQueryCriteria());
        if (CollectionUtils.isEmpty(groupTaskListResponses)) {
            return page;
        }
        // 内存分页 目前区发接口不支持分页，防止数据过多对前端造成影响，后续如果数据量大需要区发支持分页
        int totalCount = groupTaskListResponses.size();
        page.setTotalCount(totalCount);
        int start = (pageNum - 1) * pageSize;
        if (start > totalCount - 1) {
            return page;
        }
        int end = start + pageSize;
        if (end > totalCount) {
            end = totalCount;
        }

        groupTaskListResponses = groupTaskListResponses.subList(start, end);
        page.setDataList(groupTaskListResponses);
        fillMessageType(request.getQueryCriteria().getUid(), groupTaskListResponses);

        return page;
    }

    @Override
    public List<GroupTaskListResponse> marketCalendarList(MarketTaskCalenderRequest request) {

        // 营销中台——团长任务列表查询
        MarketTaskQuFaRequest quFaRequest
                = MarketTaskQuFaRequest.getInstance(request.getUid(), request.getUnionId(), request.getDate());
        List<GroupTaskListResponse> marketList = groupTaskDependency.marketCalendarList(quFaRequest);
        fillMessageType(request.getUid(), marketList);

        // 统一作业平台——团长任务列表查询
        MarketTaskScrmRequest scrmRequest
                = MarketTaskScrmRequest.getInstance(request.getUid(), request.getUnionId(), request.getDate());
        List<MarketCalendarScrmResponse> records = scrmServerHttpUtil.postCommonListZeroForMapping(
                QuFaHttpConstant.MARKET_CALENDAR_LIST_FOR_SCRM, "records",
                JSON.toJSONString(scrmRequest), MarketCalendarScrmResponse.class);

        // 数据加工返回
        List<GroupTaskListResponse> result = new ArrayList<>(marketList.size() + records.size());
        result.addAll(marketList);
        records.forEach(item -> {
            GroupTaskListResponse taskListResponse = new GroupTaskListResponse();
            taskListResponse.setTaskPhaseId(item.getEventId());
            taskListResponse.setTaskPhaseName(item.getEventName());
            taskListResponse.setTaskPhaseDescription(item.getIrisInterest());
            taskListResponse.setWebpageThumbnailImgUrl(item.getIrisPicUrl());
            taskListResponse.setTaskPhaseStatus(item.getStatus());
            taskListResponse.setDetailJumpUrl(item.getIrisUrl());
            taskListResponse.setTaskPhaseStartTime(item.getStartTime());
            taskListResponse.setTaskPhaseEndTime(item.getEndTime());
            taskListResponse.setTaskType(2);
            result.add(taskListResponse);
        });

        Map<String, Integer> calendarConfig = getMarketCalendarConfig();
        // 活动状态枚举：2=待上线(未开始)，3=已上线(进行中)，4=已下线(已结束)
        // 需要按照 进行中>未开始>已结束 来排序，先改变一下进行中的优先级
        Map<Integer, Integer> of = ImmutableMap.of(3, 1);

        List<GroupTaskListResponse> top = result.stream().filter(i -> {
            String topKey = getTopKey(i);
            return calendarConfig.containsKey(topKey);
        }).sorted(Comparator.comparingInt((GroupTaskListResponse i) -> {
            String topKey = getTopKey(i);
            return calendarConfig.getOrDefault(topKey.toString(), Integer.MAX_VALUE);
        })).collect(Collectors.toList());

        result.removeAll(top);
        List<GroupTaskListResponse> notTop = result.stream()
                .sorted(Comparator.comparingInt(a -> of.getOrDefault(a.getTaskPhaseStatus(), a.getTaskPhaseStatus())))
                .collect(Collectors.toList());
        CollectionUtils.addAll(top, notTop);
        return top;
    }

    private static String getTopKey(GroupTaskListResponse i) {
        Integer taskTargetEvaluation = i.getTaskTargetEvaluation();
        StringBuilder builder = new StringBuilder();
        if (taskTargetEvaluation != null) {
            builder.append(taskTargetEvaluation).append("_");
        }
        builder.append(i.getTaskPhaseId());
        return builder.toString();
    }

    private Map<String, Integer> getMarketCalendarConfig() {
        TCommonKvConfigBatchQueryRequest queryRequest = new TCommonKvConfigBatchQueryRequest();
        queryRequest.setConfigKeyList(Arrays.asList(MarketCalendarConstants.CALENDAR_SORT_CONFIG_KEY));

        List<TCommonKvConfigDTO> configList = basicDependency.batchQueryCommonKV(queryRequest);
        if (CollectionUtil.isEmpty(configList)) {
            return Collections.emptyMap();
        }

        String configValue = configList.get(0).getConfigValue();
        if (StrUtil.isBlank(configValue)) {
            return Collections.emptyMap();
        }

        Map<String, Integer> indexMap = Maps.newHashMap();
        String[] split = configValue.split("\n");
        //只能置顶10个
        int limit = split.length > 10 ? 10 : split.length;
        for (int i = 0; i < limit; i++) {
            indexMap.put(split[i].replaceAll(" ", ""), i);
        }

        return indexMap;
    }


    /**
     * 填充用户订阅消息情况
     *
     * @param uid
     * @param groupTaskListResponses
     */
    private void fillMessageType(String uid, List<GroupTaskListResponse> groupTaskListResponses) {
        // 报名的活动id列表
        List<String> activityIdList = groupTaskListResponses.stream().map(GroupTaskListResponse::getTaskPhaseId)
                .map(String::valueOf)
                .collect(Collectors.toList());
        if (CollectionUtils.isEmpty(activityIdList)) {
            return;
        }
        // 可报名列表，需要知道消息订阅的情况
        ActivityQuerySubscribeRequest subscribeRequest = new ActivityQuerySubscribeRequest();
        subscribeRequest.setUid(uid);
        subscribeRequest.setActivityIdList(activityIdList);
        List<ActivityQuerySubscribeResponse> sl = activityMessageDependency.querySubscribe(subscribeRequest);
        if (CollectionUtils.isNotEmpty(sl)) {
            Map<String, List<Integer>> sMap = sl.stream()
                    .collect(Collectors.toMap(ActivityQuerySubscribeResponse::getActivityId,
                            ActivityQuerySubscribeResponse::getMessageTypeList));
            for (GroupTaskListResponse r : groupTaskListResponses) {
                r.setMessageTypeList(sMap.get(String.valueOf(r.getTaskPhaseId())));
            }
        }
    }

    @Override
    public PaginationResponse<GroupTaskListResponse> listEnded(
            PaginationRequest<GroupTaskListNewRequest> request) {
        PaginationResponse<GroupTaskListResponse> page = groupTaskDependency.listEnded(request);
        if (CollectionUtils.isNotEmpty(page.getDataList())) {
            // 可报名列表，需要知道消息订阅的情况
            fillMessageType(request.getQueryCriteria().getUid(), page.getDataList());
        }
        return page;
    }


}
